
package com.be.beadmin.device.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.device.dto.output.EnergyInfoExcelEx;
import com.be.beadmin.device.entity.EnergyInfo;
import com.be.beadmin.device.entity.EnergyInfo_;
import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.device.utils.ExcelListener;
import lombok.RequiredArgsConstructor;
import com.be.beadmin.device.mapper.EnergyInfoMapperEx;
import com.be.beadmin.device.repository.EnergyInfoRepository;
import com.be.beadmin.device.service.EnergyInfoService;
import com.be.beadmin.device.dto.input.EnergyInfoDto;
import com.be.beadmin.device.dto.output.EnergyInfoEx;
import com.be.beadmin.device.dto.input.EnergyInfoQueryCriteria;
import com.be.beadmin.device.mapper.EnergyInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.be.beadmin.device.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Order;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
* @description 服务实现
* @author chenxu
* @date 2023-08-30
**/
@Service
@RequiredArgsConstructor
public class EnergyInfoServiceImpl implements EnergyInfoService {

    @Autowired
    private  EnergyInfoRepository energyInfoRepository;
    @Autowired
    private  EnergyInfoMapper energyInfoMapper;
    @Autowired
    private  EnergyInfoMapperEx energyInfoExMapper;

    @Override
    public Page<EnergyInfoEx> getEnergyInfoByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<EnergyInfo> page = energyInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(EnergyInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(EnergyInfo_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<EnergyInfoEx> page1 = page.map(energyInfoExMapper::toEntity);
            return page1;

    }

    @Override
    public void addEnergyInfo(EnergyInfoDto energyInfoDto) {
            EnergyInfo result = energyInfoRepository.findEnergyInfoByIdAndDelete(energyInfoDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("EnergyInfo不存在,请重新查询");
            }
            EnergyInfo energyInfo = energyInfoMapper.toEntity(energyInfoDto);
            energyInfoRepository.save(energyInfo);
    }

    @Override
    public void updateEnergyInfo(EnergyInfoDto energyInfoDto) {
            EnergyInfo energyInfo = energyInfoRepository.findEnergyInfoById(energyInfoDto.getId());
            energyInfo = energyInfoMapper.toEntity(energyInfoDto);
            energyInfoRepository.save(energyInfo);
    }


    @Override
    public void delEnergyInfo(String id) {
        EnergyInfo energyInfo = energyInfoRepository.findEnergyInfoById(id);
        energyInfo.setDelete(1);
        energyInfoRepository.save(energyInfo);
    }

    @Override
    public void delEnergyInfos (List<String> ids) { }

    @Override
    public void uploadEnergyInfo(MultipartFile file) {
        ExcelListener<EnergyInfoExcelEx> excelListener = new ExcelListener<>();
        try{
            ExcelReader excelReader = EasyExcelFactory.read(file.getInputStream(),EnergyInfoExcelEx.class ,excelListener).headRowNumber(1).build();
            excelReader.readAll();
            excelReader.finish();
        }catch (ExcelDataConvertException e){
            throw new BeadminException("表中数据类型有误");
        }catch (Exception e) {
            System.out.println(e);
            throw new BeadminException("解析失败");
        }

        List<EnergyInfoExcelEx> dataList = excelListener.getDatas();
        for (EnergyInfoExcelEx item : dataList){
            EnergyInfo energyInfo = new EnergyInfo();
            energyInfo.setDeviceName(item.getDeviceName());
            energyInfo.setDeviceId(item.getDeviceId());
            energyInfo.setArea(item.getArea());
            energyInfo.setPeriod(item.getPeriod());
            energyInfo.setValue(item.getValue());
            energyInfo.setPeriod(item.getPeriod());
            energyInfo.setYear(item.getYear());
            energyInfo.setMonth(item.getMonth());
            energyInfo.setDay(item.getDay());
            energyInfo.setEnergyItem(item.getEnergyItem());
            energyInfoRepository.save(energyInfo);
        }
    }

    @Override
    public String[] getAllDevice() {
        return energyInfoRepository.findAllDeviceName();
    }
}